package com.qing.expert.modules.user.controller;

import com.qing.expert.common.annotation.OperationLog;
import com.qing.expert.common.response.R;
import com.qing.expert.common.utils.JwtUtils;
import com.qing.expert.modules.user.entity.User;
import com.qing.expert.modules.user.service.UserService;
import com.qing.expert.modules.user.vo.request.LoginRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证控制器
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private UserService userService;

    @Resource
    private JwtUtils jwtUtils;

    @OperationLog(action = "用户登录", detail = "用户登录操作")
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        log.info("收到微信登录请求，code: {}, userInfo: {}", loginRequest.getCode(), loginRequest.getUserInfo());

        // 1. 微信登录
        User user = userService.wxLogin(
                loginRequest.getCode(),
                loginRequest.getUserInfo() != null ? loginRequest.getUserInfo().getNickName() : null,
                loginRequest.getUserInfo() != null ? loginRequest.getUserInfo().getAvatarUrl() : null);

        // 2. 生成token
        String token = jwtUtils.generateToken(user.getUserId(), user.getRole());

        // 3. 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("userId", user.getUserId());
        result.put("role", user.getRole());
        result.put("token", token);
        result.put("userInfo", user);

        log.info("登录成功，userId: {}", user.getUserId());
        return R.ok(result);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        log.info("收到登出请求，userId: {}", userId);

        userService.logout(userId);

        return R.ok();
    }
}